// rnc
import React, {Component} from 'react';
import {Dimensions, FlatList, Image, Text, View} from 'react-native';

const {width, height} = Dimensions.get('screen');

const rpx = x => (width / 750) * x;

export default class App extends Component {
  douyu = 'http://capi.douyucdn.cn/api/v1/live?limit=20&offset=0';

  state = {data: []};

  componentDidMount() {
    fetch(this.douyu)
      .then(res => res.json())
      .then(res => {
        console.log(res);
        this.setState({data: res.data});
      });
  }

  render() {
    return (
      <FlatList
        data={this.state.data}
        keyExtractor={(item, index) => index + ''}
        renderItem={this._renderItem}
        numColumns={2}
      />
    );
  }

  _renderItem = ({item}) => {
    const space = 10;
    const box_w = rpx(750 - 10 * 3) / 2;

    const online =
      item.online >= 1e4 ? (item.online / 1e4).toFixed(1) + '万' : item.online;

    return (
      <View
        style={{width: box_w, marginLeft: rpx(space), marginTop: rpx(space)}}>
        <View style={{borderRadius: 5, overflow: 'hidden'}}>
          <Image
            source={{uri: item.room_src}}
            style={{width: '100%', height: box_w * 0.55}}
          />
          <Text
            style={{
              position: 'absolute',
              right: 0,
              color: 'white',
              padding: 2,
              backgroundColor: 'rgba(0,0,0,0.2)',
              left: 0,
              textAlign: 'right',
            }}>
            {online}
          </Text>
          <Text
            style={{
              position: 'absolute',
              color: 'white',
              bottom: 0,
              padding: 4,
            }}>
            {item.nickname}
          </Text>
        </View>
        <Text
          style={{fontSize: rpx(30), margin: 2, color: 'gray'}}
          numberOfLines={1}>
          {item.room_name}
        </Text>
      </View>
    );
  };
}
